package mysql

import (
	"bluebell/models"
	"database/sql"
	"errors"
	"go.uber.org/zap"
	"time"
)

// 初始化帖子统计（使用默认时间）
func InitPostStats(postID int64) error {
	// 使用DEFAULT值让数据库自动填充时间
	sqlStr := `INSERT INTO post_stats (post_id) VALUES (?)`
	_, err := db.Exec(sqlStr, postID)
	if err != nil {
		zap.L().Error("初始化帖子统计失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}

// 增加浏览量（简化SQL，不再处理NULL）
func IncrementViewCount(postID int64) error {
	now := time.Now().UTC()
	sqlStr := `
		INSERT INTO post_stats (post_id, view_count, last_viewed_at) 
		VALUES (?, 1, ?)
		ON DUPLICATE KEY UPDATE 
			view_count = view_count + 1,
			last_viewed_at = ?,
			updated_at = ?`

	_, err := db.Exec(sqlStr, postID, now, now, now)
	if err != nil {
		zap.L().Error("增加浏览量失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}

// 增加点赞量（其他类似操作都保持相同模式）
func IncrementLikeCount(postID int64) error {
	now := time.Now().UTC()
	sqlStr := `
		INSERT INTO post_stats (post_id, like_count, last_liked_at) 
		VALUES (?, 1, ?)
		ON DUPLICATE KEY UPDATE 
			like_count = like_count + 1,
			last_liked_at = ?,
			updated_at = ?`

	_, err := db.Exec(sqlStr, postID, now, now, now)
	if err != nil {
		zap.L().Error("增加点赞量失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}

// 获取帖子统计信息（简化查询）
func GetPostStats(postID int64) (*models.PostStats, error) {
	sqlStr := `
		SELECT 
			post_id, 
			view_count, 
			like_count, 
			collect_count, 
			comment_count,
			last_viewed_at,
			last_liked_at,
			last_collected_at,
			last_commented_at,
			created_at, 
			updated_at
		FROM post_stats
		WHERE post_id = ?`

	var stats models.PostStats
	err := db.Get(&stats, sqlStr, postID)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			// 返回默认值而不是空结构
			return &models.PostStats{
				PostID:          postID,
				LastViewedAt:    models.ZeroTime,
				LastLikedAt:     models.ZeroTime,
				LastCollectedAt: models.ZeroTime,
				LastCommentedAt: models.ZeroTime,
			}, nil
		}
		zap.L().Error("获取帖子统计失败",
			zap.Int64("postID", postID),
			zap.Error(err))
		return nil, err
	}
	return &stats, nil
}

// 增加评论量和更新最后评论时间
func IncrementCommentCount(postID int64) error {
	now := time.Now().UTC()
	sqlStr := `
		INSERT INTO post_stats (post_id, comment_count, last_commented_at) 
		VALUES (?, 1, ?)
		ON DUPLICATE KEY UPDATE 
			comment_count = comment_count + 1,
			last_commented_at = ?,
			updated_at = ?`

	_, err := db.Exec(sqlStr, postID, now, now, now)
	if err != nil {
		zap.L().Error("增加评论量失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}

// 增加收藏量和更新最后收藏时间
func IncrementCollectCount(postID int64) error {
	now := time.Now().UTC()
	sqlStr := `
		INSERT INTO post_stats (post_id, collect_count, last_collected_at) 
		VALUES (?, 1, ?)
		ON DUPLICATE KEY UPDATE 
			collect_count = collect_count + 1,
			last_collected_at = ?,
			updated_at = ?`

	_, err := db.Exec(sqlStr, postID, now, now, now)
	if err != nil {
		zap.L().Error("增加收藏量失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}

// 获取最近有评论的帖子ID
func GetRecentlyCommentedPostIDs(limit int) ([]int64, error) {
	sqlStr := `
		SELECT post_id 
		FROM post_stats 
		WHERE last_commented_at IS NOT NULL 
		ORDER BY last_commented_at DESC
		LIMIT ?`

	var postIDs []int64
	err := db.Select(&postIDs, sqlStr, limit)
	if err != nil {
		zap.L().Error("获取最近评论帖子失败", zap.Error(err))
		return nil, err
	}
	return postIDs, nil
}

// 删除帖子统计（当帖子被删除时调用）
func DeletePostStats(postID int64) error {
	sqlStr := `DELETE FROM post_stats WHERE post_id = ?`
	_, err := db.Exec(sqlStr, postID)
	if err != nil {
		zap.L().Error("删除帖子统计失败",
			zap.Int64("postID", postID),
			zap.Error(err))
	}
	return err
}
